/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.globussoft.xml;
/**
 *
 * @author Dj
 */
import java.io.FileOutputStream;
import java.io.IOException;


import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Text;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

import java.io.FileNotFoundException;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;
public class SettingsXml 
{
         private static String username;
         private static String pass;
         private static float quota = (float) 2.0;
         private static boolean rempass;
         private static boolean encryptpom;
         private static boolean encryptperson;
         private static boolean expertmode;
         private static boolean initialidle;
         private static boolean initialnow;
         private static String initsize=null;
         private static long initfiles=0;
         private static long setSizeSpeed=0;
         private static int speed;
         Document dom=null;
         private static String projectName ="PomBlast";

        public static void setProjectName(String projectName)
        {
            SettingsXml.projectName=projectName;            
        }
        public static String getProjectName()
        {
            return projectName;
        }


      public static String getUser() {
        SettingsXml setting = new SettingsXml();
        try{
        setting.ReadGeneralXml("settings.xml");
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return username;
      }
      public void setUser(String username) {
            this.username = username;
         }

     public float getQuota(){
         return quota;
     }

     public void setQuota(float quota){
         this.quota=quota;
     }

      public String getPassword() {

            return pass;

      }

      public void setPassword(String pass) {

            this.pass = pass;

      }

      public boolean getRememberPass() {

            return rempass;

      }

      public void setRememberPass(boolean rempass) {

            SettingsXml.rempass = rempass;
          

      }
       public boolean getEncyptPom() {

            return encryptpom;

      }

      public void setEncyptPom(boolean encryptpom) {

            SettingsXml.encryptpom = encryptpom;

      }

      public boolean getEncryptPersonal() {

            return encryptperson;

      }

      public void setEncryptPersonal(boolean encryptperson) {

            SettingsXml.encryptperson = encryptperson;

      }
      public boolean getexpertmode() {

            return expertmode;

      }
      public void setexpertmode(boolean expertmode) {

            SettingsXml.expertmode = expertmode;
         }

      public boolean getinitialidle() {

            return initialidle;

      }

      public void setinitialidle(boolean initialidle) {

            SettingsXml.initialidle = initialidle;

      }

      public boolean getinitialnow() {

            return initialnow;

      }

      public void setinitialnow(boolean initialnow) {

            SettingsXml.initialnow = initialnow;

      }

      public long getInitFiles(){
          return initfiles;
      }

      public void setInitFiles(long initfiles){
          SettingsXml.initfiles = initfiles;
      }

      public String getInitSize(){
       return initsize;
      }

      public void setInitSize(String initsize){
          SettingsXml.initsize=initsize;
      }

      public long getSizeSpeed()
      {
          return setSizeSpeed;
      }

      public void setSizeSpeed(long setSizeSpeed)
      {
          SettingsXml.setSizeSpeed=setSizeSpeed;
      }
      public int getSpeed() {

            return speed;

      }

      public void setSpeed(int speed) {

            SettingsXml.speed = speed;

      }

  public  void writeGeneralXml(String filename) throws ParserConfigurationException
  {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              try {
                  DocumentBuilder db = dbf.newDocumentBuilder();
                  dom = db.newDocument();
                  Element rootElement = dom.createElement("Configuration-Settings");
                 // dom.appendChild(rootElement);
                  Element generalElement = dom.createElement("Configuration");
                  generalElement=createGeneralElement(generalElement,"UserName",username);
                  generalElement=createGeneralElement(generalElement,"Password",""+pass);
                  generalElement=createGeneralElement(generalElement,"Remember-Password",""+rempass);
                  generalElement=createGeneralElement(generalElement,"Encrypt-Pom-Bit",""+encryptpom);
                  generalElement=createGeneralElement(generalElement,"Encrypt-Person-Bit",""+encryptperson);
                  generalElement=createGeneralElement(generalElement,"Speed",""+speed);
                  generalElement=createGeneralElement(generalElement,"Expert-Mode",""+expertmode);
                  generalElement=createGeneralElement(generalElement,"Initial-Back-Idle",""+initialidle);
                  generalElement=createGeneralElement(generalElement,"Initial-Back-Now",""+initialnow);
                  generalElement=createGeneralElement(generalElement,"Quota",""+quota);
                  generalElement=createGeneralElement(generalElement,"ProjectName",""+projectName);
                  rootElement.appendChild(generalElement);
                  dom.appendChild(rootElement);

                 try{
                  printToFile(dom,filename);
                 }catch(Exception ex){}



            }catch(ParserConfigurationException pce) {

                //  System.out.println("Error while trying to instantiate DocumentBuilder " + pce);

                  System.exit(1);

             }


      }

               /**
	 * Helper method which creates a XML element
	 * @param xmlgeneralstore The SetXmlGeneralStore for which we need to create an xml representation
	 * @return XML element snippet representing a SetXmlGeneralStore
	 */

      private Element createGeneralElement(Element generalElement,String property,String value)
      {


          //create Status element and Status text node and attach it to generalElement
            Element statusElement = dom.createElement(property);

            Text statusText = dom.createTextNode(value);

            statusElement.appendChild(statusText);

            generalElement.appendChild(statusElement);


            return generalElement;

      }

       private void printToFile(Document dom,String filename) throws FileNotFoundException, IOException{
           try
            {

                 OutputFormat format = new OutputFormat(dom);
                  format.setIndenting(true);
                  //URL mySource = XmlGeneralStore.class.getProtectionDomain().getCodeSource().getLocation();
                //  File sourceFile = new File(".");
                 boolean success;
                 String source=System.getProperty("user.home");
                 String dir=source+"\\"+projectName;
                 File sourceFile = new File(dir);
                 if(!sourceFile.exists())
                 {
                     success=new File(dir).mkdir();
                 }


                // attach text file to application directory(.class file)
                  String xmlfile = dir+"\\"+filename;

               //to generate output to console use this serializer

              //XMLSerializer serializer = new XMLSerializer(System.out, format);

             //to generate a file output use fileoutputstream instead of system.out

                  XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(xmlfile)), format);
                  serializer.serialize(dom);

              } catch(IOException ie)
              {
                 ie.printStackTrace();
              }

      }

       //reading the xml file code her
public void ReadGeneralXml(String filename) 
{
   // String storegenerralxml[]=new String[10];
  try {
      // URL mySource = XmlGeneralStore.class.getProtectionDomain().getCodeSource().getLocation();
     // File sourceFile = new File(".");
     // attach text file to application directory(.class file)
      //String xmlfile = sourceFile.getAbsolutePath()+"\\"+"generalsettings.xml";
	  boolean success;
      String    source=System.getProperty("user.home");
      String dir=source+"\\"+projectName;
      File fXmlFile = new File(dir+"\\"+filename);
      if(fXmlFile.isFile())
      {
	  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	  Document doc = dBuilder.parse(fXmlFile);
	  doc.getDocumentElement().normalize();

	 // System.out.println("General Settings :" + doc.getDocumentElement().getNodeName());
	  NodeList nList = doc.getElementsByTagName("Configuration");
	//  System.out.println("-----------------------");

	  for (int temp = 0; temp < nList.getLength(); temp++) {

	    Node nNode = nList.item(temp);

	    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

	      Element eElement = (Element) nNode;

//	     storegenerralxml[0]= getTagValue("Bandwidth",eElement);
//	     storegenerralxml[1]= getTagValue("Limit",eElement);
//	     storegenerralxml[2]=getTagValue("Throttle",eElement).trim();

         username=getTagValue("UserName",eElement).trim();
         pass=getTagValue("Password",eElement).trim();
         String rempasstemp=getTagValue("Remember-Password",eElement).trim();
         if(rempasstemp.equals("false"))
             rempass=false;
         else
             rempass=true;
         String encryptpomtemp=getTagValue("Encrypt-Pom-Bit",eElement).trim();
         if(encryptpomtemp.equals("false"))
             encryptpom=false;
         else
             encryptpom=true;
         String encryptpersontemp=getTagValue("Encrypt-Person-Bit",eElement).trim();
         if(encryptpersontemp.equals("false"))
             encryptperson=false;
         else
             encryptperson=true;
         String expertmodetemp=getTagValue("Expert-Mode",eElement).trim();
         if(expertmodetemp.equals("false"))
             expertmode=false;
         else
             expertmode=true;
         String initialidletemp=getTagValue("Initial-Back-Idle",eElement).trim();
         if(initialidletemp.equals("false"))
             initialidle=false;
         else
             initialidle=true;

         String initialnowtemp=getTagValue("Initial-Back-Now",eElement).trim();
         if(initialnowtemp.equals("false"))
             initialnow=false;
         else
             initialnow=true;
         String speedtemp=getTagValue("Speed",eElement).trim();
         speed=Integer.parseInt(speedtemp);

         String quotaString=getTagValue("Quota",eElement).trim();
         quota= Float.parseFloat(quotaString);

         projectName=getTagValue("ProjectName",eElement).trim();

	    }
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
    //return storegenerralxml;
}

private static String getTagValue(String sTag, Element eElement)
 {
	  NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	  Node nValue = (Node) nlList.item(0);

	  return nValue.getNodeValue();

 }
public static void main(String[]arg)
{
    SettingsXml setting = new SettingsXml();
    try{
//        setting.setUser("sunilkumar");
//        setting.setPassword("sunilkumar");
//        setting.writeGeneralXml("Test.xml");
        setting.ReadGeneralXml("settings.xml");
        System.out.println(setting.getUser());
    }catch(Exception ex)
    {
        ex.printStackTrace();
    }
}
}
 
